package com.igeekhome.shopservice.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.igeekhome.shop.pojo.TbItem;
import com.igeekhome.shop.pojo.TbItemDesc;
import com.igeekhome.shopservice.mapper.ItemDescMapper;
import com.igeekhome.shopservice.mapper.ItemMapper;
import com.igeekhome.shopservice.service.IItemService;
import com.igeekhome.shopservice.vo.ItemAddVo;
import com.igeekhome.shopservice.vo.ItemQueryVo;
import com.igeekhome.util.CustomPageInfo;

import com.igeekhome.util.IDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class ItemserviceImpl implements IItemService {
    @Resource
    public ItemMapper itemMapper;

    @Resource
    private ItemDescMapper itemDescMapper;

    @Override
    public CustomPageInfo selectAll(Integer page, Integer limit, ItemQueryVo item) {
        PageHelper.startPage(page, limit);
        List<TbItem> tbItems = itemMapper.selectByQuery(item);
        PageInfo<TbItem> pageInfo = new PageInfo(tbItems);
        long total = pageInfo.getTotal();
        return new CustomPageInfo(tbItems,total);
}

    @Override
    public void addItemAndDesc(ItemAddVo item) {
        Long id = IDUtil.generateId();
        TbItem tbItem = new TbItem();
        tbItem.setId(id);
        tbItem.setTitle(item.getTitle());
        tbItem.setSellPoint(item.getSellPoint());
        tbItem.setPrice(item.getPrice());
        tbItem.setBarcode(item.getBarcode());
        tbItem.setCid(item.getCid());
        tbItem.setImage(item.getImage());
        tbItem.setNum(item.getNum());
        //补全item参数，上下架(默认上架)、创建时间、更新时间
        tbItem.setStatus(1);
        tbItem.setCreated(new Date());
        tbItem.setUpdated(tbItem.getCreated());
        //保存商品信息TbItem（自增长主键返回）
        itemMapper.insert(tbItem);
        //构建商品详情对象并保存（补全参数：商品id、创建时间、更新时间）
        TbItemDesc tbItemDesc = new TbItemDesc();
        tbItemDesc.setItemId(id);
        tbItemDesc.setItemDesc(item.getContent());
        tbItemDesc.setCreated(new Date());
        tbItemDesc.setUpdated(tbItemDesc.getCreated());
        itemDescMapper.insert(tbItemDesc);
    }
}
